package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.domain.OrderSetting;
import com.itheima.entity.Result;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 预约设置数据控制层
 */
@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Reference
    private OrderSettingService orderSettingService;

    /**
     * 文件上传
     *
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile excelFile) {
        try {
            List<String[]> excels = POIUtils.readExcel(excelFile);
            List<OrderSetting> orderSettings = new ArrayList<>();
            for (String[] excel : excels) {
                OrderSetting orderSetting = new OrderSetting(new Date(excel[0]), Integer.parseInt(excel[1]));
                orderSettings.add(orderSetting);
            }
            orderSettingService.addOrUpdateBatchOrderSetting(orderSettings);
            return Result.success(MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.failed(MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }

    @GetMapping("/findOrderSetting")
    public Result findOrderSetting(String time) {
        try {
            List<Map<String, String>> orderSettings = orderSettingService.findOrderSettingByDate(time);
            return Result.success(MessageConstant.QUERY_ORDER_SUCCESS, orderSettings);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(MessageConstant.QUERY_ORDER_FAIL);
        }
    }

    /**
     * 根据日期修改或者设置单个预约数据
     *
     * @param dateString
     * @param number
     * @return
     */
    @GetMapping("/edit")
    public Result edit(String dateString, Integer number) {
        try {
            orderSettingService.addOrUpdateOrderSetting(dateString, number);
            return Result.success(MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(MessageConstant.ORDERSETTING_FAIL);
        }
    }
}
